<template>
  <el-upload
    class="avatar-uploader comp-img-upload"
    :ref="model"
    :on-change="uploadChange"
    :on-success="uploadSuccess"
    :on-error="uploadError"
    :auto-upload="false"
    :data="imgUploadParam"
    :action="UPLOAD_SERVER"
    :show-file-list="false">
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
import { DEFAULT } from 'services/Config'
export default {
  name: 'CompImgUpload',
  data () {
    return {
      UPLOAD_SERVER: DEFAULT.UPLOAD_SERVER,
      IMG_SRC_SERVER: DEFAULT.IMG_SRC_SERVER,
      file: {},
      imageUrl: ''
    }
  },
  props: {
    imgsrc: [ String, Object ],
    uploadImg: Boolean,
    clearAllImg: Boolean,
    model: String,
    OSSPolicy: Object,
    isUploadOne: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    imgsrc: {
      immediate: true,
      handler (v) {
        if (v && typeof v === 'string') this.imageUrl = `${this.IMG_SRC_SERVER + v}`
      }
    },
    uploadImg (v) {
      this.$refs[this.model].submit()
    },
    clearAllImg () {
      this.file = {}
      this.imageUrl = ''
      this.$refs[this.model].clearFiles()
    }
  },
  computed: {
    // 图片上传参数
    imgUploadParam () {
      return {
        Filename: `user/${this.file.name}`,
        key: `user/${this.file.name}`,
        OSSAccessKeyId: this.OSSPolicy.accessid,
        callback: this.OSSPolicy.callback,
        policy: this.OSSPolicy.policy,
        success_action_status: '200',
        signature: this.OSSPolicy.signature
      }
    }
  },
  methods: {
    uploadChange (file, fileList) {
      if (fileList && fileList.length > 1 && this.isUploadOne) {
        fileList.shift()
      }
      // 如果不是选择新图片，返回
      if (file === this.file) return
      this.imageUrl = file.url
      if (file) {
        this.file = file
        const param = {
          file: file,
          model: this.model
        }
        this.$emit('fileChange', param)
      }
    },
    uploadSuccess (respone) {
      const param = {
        data: `/${respone.filename}`,
        model: this.model
      }
      this.$emit('success', param)
    },
    uploadError (e) {
      const param = {
        data: e,
        model: this.model
      }
      this.$emit('error', param)
    }
    // uploadExceed () {
    //   this.$message.warning('超过最大上传个数')
    // }
  }
}
</script>

<style lang="scss">
@import "src/styles/config/components.scss";

@include b(img-upload) {}
</style>
